package com.starblink.login.createaccount.register.ui

import android.app.Activity
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.android.common.utils.PasswordUtils
import com.starblink.basic.style.R
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.CreateAccountMutation
import kotlinx.coroutines.launch

class CreateAccountRegisterVM : BaseViewModel() {

    fun register(email: String, psw: String, username: String) {
        // email｜psw｜username 都是有效值
        viewModelScope.launch {
            //请求：注册账号，返回token
            val response = SkGqlClient.skMutation(
                CreateAccountMutation(
                    email, username, PasswordUtils.generatePassMD5(psw), inviteCode = ""
                ),
                showDefaultLoading = true
            )
            if (response?.data != null && response.data!!.createAccount != null) {
                LoginManager.refreshTokenAndUserInfoAfterLoginSuccess(
                    response.data!!.createAccount!!,
                    onSuccess = {
                        YYLogUtils.e("注册并登录成功", "dss")
                        toast(R.string.login_success)
                        // 先返回至CreateAccountInputEmailActivity页面，再设置返回值，返回至登录页面
                        ActivityStackManage.finishLastActivities(2)
                        ActivityStackManage.currentActivity().setResult(Activity.RESULT_OK)
                        ActivityStackManage.currentActivity().finish()
                    },
                    onFail = {
                        YYLogUtils.e("注册成功但登录失败", "dss")
                        // 注册成功但登录失败，返回登录页去登录
                        toast(CommUtils.getString(R.string.create_account_success))
                        ActivityStackManage.finishLastActivities(3)
                    }
                )
            }
        }
    }
}